#include <iostream>
#include <fstream>
#include <vector>
#include <cassert>

namespace KMeansMultiple {

    template<typename T>
    T *load_vecs(const char *filename, int &n_data, int &dim) {
        std::ifstream in(filename, std::ios::binary);
        if (!in.is_open()) {
            std::cerr << "Open file error" << std::endl;
            exit(-1);
        }

        in.read((char *) &dim, 4);

        in.seekg(0, std::ios::end);
        std::ios::pos_type ss = in.tellg();
        size_t fsize = (size_t) ss;
        n_data = (int) (fsize / (dim + 1) / 4);

        T *data = new T[(size_t) n_data * (size_t) dim];

        in.seekg(0, std::ios::beg);
        for (int i = 0; i < n_data; i++) {
            in.seekg(4, std::ios::cur);
            in.read((char *) (data + i * dim), dim * sizeof(T));
        }
        in.close();

        return data;
    }

    void save_weight_l(char *base_path, std::vector<std::vector<float>> weight_l) {
        std::ofstream out(base_path, std::ios::binary | std::ios::out);
        int n_query = (int) weight_l.size();
        int n_item = (int) weight_l[0].size();
        for (int i = 0; i < n_query; i++) {
            out.write((char *) &n_item, sizeof(unsigned));
            out.write((char *) weight_l[i].data(), n_item * sizeof(unsigned));
        }
        out.close();
        printf("save weight_l success\n");
    }

}
